package com.atguigu.gulimall.seckill.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberResponseVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @program: gulimall
 * @description: TODO
 * @author: YuWenYi
 * @create: 2021-07-18 20:17
 **/
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberResponseVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        // 这个请求直接放行
        // 原因:因为rabbitMQ监听任务是由新开的线程处理的,因此它通过feign发送请求会丢失请求头,因此这个过滤器会拦截到这个请求
        // 如果不想自己再去给feign加上请求头,那么就需要对这些请求进行放行操作!
        boolean match = new AntPathMatcher().match("/kill", uri);
        if(match){
            HttpSession session = request.getSession();
            MemberResponseVo memberRsepVo = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
            if(memberRsepVo != null){
                threadLocal.set(memberRsepVo);
                return true;
            }else{
                // 没登陆就去登录
                session.setAttribute("msg", AuthServerConstant.NOT_LOGIN);
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            }
        }
        return true;
    }
}